import React, { useState, useRef, useCallback, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { gsap } from 'gsap';
import './GalleryModal.css';
import FabricCanvas from '../FabricCanvas';

interface CanvasImage {
  id: string;
  src: string;
  x: number;
  y: number;
  width: number;
  height: number;
  rotation: number;
  scale: number;
  selected: boolean;
}

interface GalleryModalProps {
  isOpen: boolean;
  onClose: () => void;
  imageToEdit?: string;
  onSave?: (imageData: string) => void;
  onDownload?: (imageData: string) => void;
}

const GalleryModal: React.FC<GalleryModalProps> = ({
  isOpen,
  onClose,
  imageToEdit,
  onSave,
  onDownload
}) => {
  const [images, setImages] = useState<CanvasImage[]>([]);
  const [activeTool, setActiveTool] = useState<string>('select');
  const [selectedImageId, setSelectedImageId] = useState<string | null>(null);
  const [isLoadingImage, setIsLoadingImage] = useState<boolean>(false);
  const [brushColor, setBrushColor] = useState<string>('#000000');
  const [brushWidth, setBrushWidth] = useState<number>(1);
  const [eraseColor, setEraseColor] = useState<string>('#ffffff');
  const [eraseWidth, setEraseWidth] = useState<number>(20);
  const [showBrushColorDropdown, setShowBrushColorDropdown] = useState<boolean>(false);
  const [showEraseColorDropdown, setShowEraseColorDropdown] = useState<boolean>(false);
  
  // 颜色选项
  const brushColors = [
    { value: '#000000', name: '黑色' },
    { value: '#ffffff', name: '白色' },
    { value: '#ff0000', name: '红色' },
    { value: '#00ff00', name: '绿色' },
    { value: '#0000ff', name: '蓝色' },
    { value: '#ffff00', name: '黄色' },
    { value: '#ff00ff', name: '紫色' },
    { value: '#00ffff', name: '青色' },
    { value: '#ffa500', name: '橙色' },
    { value: '#808080', name: '灰色' }
  ];
  
  const eraseColors = [
    { value: '#ffffff', name: '白色' },
    { value: '#000000', name: '黑色' }
  ];
  
  const canvasRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const fabricCanvasRef = useRef<any>(null);
  
  // GSAP 动画 refs
  const modalRef = useRef<HTMLDivElement>(null);
  const toolbarRef = useRef<HTMLDivElement>(null);
  const canvasContainerRef = useRef<HTMLDivElement>(null);

  // 处理文件上传
  const handleFileUpload = useCallback((files: FileList) => {
    if (fabricCanvasRef.current) {
      (fabricCanvasRef.current as any).handleFileUpload(files);
    }
  }, []);

  // 处理拖拽上传
  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    const files = e.dataTransfer.files;
    if (files.length > 0) {
      handleFileUpload(files);
    }
  }, [handleFileUpload]);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
  }, []);

  // 键盘快捷键处理
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Delete' || e.key === 'Backspace') {
        if (fabricCanvasRef.current) {
          (fabricCanvasRef.current as any).deleteSelected();
        }
      } else if (e.key === 'Escape') {
        onClose();
      }
    };

    if (isOpen) {
      window.addEventListener('keydown', handleKeyDown);
    }
    
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, onClose]);

  // 处理传递过来的图片，自动加载到画布
  useEffect(() => {
    if (isOpen && imageToEdit && fabricCanvasRef.current) {
      // 先清空画布内容，避免重复图层
      fabricCanvasRef.current.clear();
      setImages([]);
      setSelectedImageId(null);
      
      setIsLoadingImage(true);
      
      const loadImageToCanvas = async () => {
        try {
          let file: File;
          
          if (imageToEdit.startsWith('data:')) {
            const response = await fetch(imageToEdit);
            const blob = await response.blob();
            file = new File([blob], 'edit-image.png', { type: 'image/png' });
          } else {
            const response = await fetch(imageToEdit);
            const blob = await response.blob();
            file = new File([blob], 'edit-image.png', { type: 'image/png' });
          }
          
          const fileList = {
            0: file,
            length: 1,
            item: (index: number) => index === 0 ? file : null,
            [Symbol.iterator]: function* () {
              yield file;
            }
          } as FileList;
          
          await handleFileUpload(fileList);
          setIsLoadingImage(false);
          
        } catch (error) {
          console.error('加载图片到画布失败:', error);
          setIsLoadingImage(false);
        }
      };
      
      const timer = setTimeout(loadImageToCanvas, 300);
      return () => clearTimeout(timer);
    }
  }, [isOpen, imageToEdit, handleFileUpload]);

  // GSAP 入场动画
  useEffect(() => {
    if (!isOpen) return;
    
    const tl = gsap.timeline();
    
    // 设置初始状态
    gsap.set(modalRef.current, { opacity: 0, scale: 0.8 });
    gsap.set(toolbarRef.current, { opacity: 0, y: -20, scale: 0.9 });
    gsap.set(canvasContainerRef.current, { opacity: 0, y: 30, scale: 0.95 });

    // 执行动画序列
    tl.to(modalRef.current, {
      opacity: 1,
      scale: 1,
      duration: 0.3,
      ease: "back.out(1.7)"
    })
    .to(toolbarRef.current, {
      opacity: 1,
      y: 0,
      scale: 1,
      duration: 0.4,
      ease: "back.out(1.7)"
    }, "-=0.2")
    .to(canvasContainerRef.current, {
      opacity: 1,
      y: 0,
      scale: 1,
      duration: 0.4,
      ease: "power2.out"
    }, "-=0.2");

    return () => {
      tl.kill();
    };
  }, [isOpen]);

  // 处理图片选择
  const handleImageSelect = useCallback((imageId: string) => {
    setSelectedImageId(imageId);
  }, []);

  // 处理图片删除
  const handleImageDelete = useCallback(() => {
    if (fabricCanvasRef.current) {
      (fabricCanvasRef.current as any).deleteSelected();
    }
  }, []);

  // 处理保存
  const handleSave = useCallback(() => {
    if (fabricCanvasRef.current) {
      try {
        const dataURL = fabricCanvasRef.current.toDataURL({
          format: 'png',
          quality: 1,
          multiplier: 1
        });
        
        if (dataURL) {
          onSave?.(dataURL);
          onClose();
        } else {
          console.error('无法生成图片数据');
        }
      } catch (error) {
        console.error('保存失败:', error);
      }
    }
  }, [onSave, onClose]);

  // 处理下载
  const handleDownload = useCallback(() => {
    if (fabricCanvasRef.current) {
      try {
        const dataURL = fabricCanvasRef.current.toDataURL({
          format: 'png',
          quality: 1,
          multiplier: 1
        });
        
        if (dataURL) {
          onDownload?.(dataURL);
        } else {
          console.error('无法生成图片数据');
        }
      } catch (error) {
        console.error('下载失败:', error);
      }
    }
  }, [onDownload]);

  // 处理清空
  const handleClear = useCallback(() => {
    if (fabricCanvasRef.current) {
      try {
        fabricCanvasRef.current.clear();
        setImages([]);
        setSelectedImageId(null);
      } catch (error) {
        console.error('清空失败:', error);
        setImages([]);
        setSelectedImageId(null);
      }
    }
  }, []);

  // 阻止背景滚动
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    
    return () => {
      document.body.style.overflow = '';
    };
  }, [isOpen]);

  // 点击外部关闭下拉框
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (!target.closest('.gallery-modal-color-dropdown')) {
        setShowBrushColorDropdown(false);
        setShowEraseColorDropdown(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }
    
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isOpen]);

  // 弹窗关闭时清理画布内容
  useEffect(() => {
    if (!isOpen && fabricCanvasRef.current) {
      // 清空画布和状态
      fabricCanvasRef.current.clear();
      setImages([]);
      setSelectedImageId(null);
      setIsLoadingImage(false);
    }
  }, [isOpen]);

  if (!isOpen) return null;

  return createPortal(
    <div className="gallery-modal-overlay" onClick={onClose}>
      <div 
        ref={modalRef} 
        className="gallery-modal" 
        onClick={(e) => e.stopPropagation()}
      >
        {/* 工具栏 */}
        <div ref={toolbarRef} className="gallery-modal-toolbar">
          <div className="gallery-modal-tool-buttons">
            <button
              className={`gallery-modal-tool-btn ${activeTool === 'select' ? 'gallery-modal-active' : ''}`}
              onClick={() => setActiveTool('select')}
              title="选择"
            >
              选择
            </button>
            <button
              className={`gallery-modal-tool-btn ${activeTool === 'brush' ? 'gallery-modal-active' : ''}`}
              onClick={() => setActiveTool('brush')}
              title="画笔"
            >
              画笔
            </button>
            <button
              className={`gallery-modal-tool-btn ${activeTool === 'erase' ? 'gallery-modal-active' : ''}`}
              onClick={() => setActiveTool('erase')}
              title="涂抹"
            >
              涂抹
            </button>
            
            {/* 画笔颜色选择 - 只在画笔模式下显示 */}
            {activeTool === 'brush' && (
              <div className="gallery-modal-color-picker">
                <label>颜色:</label>
                <div className="gallery-modal-color-dropdown">
                  <button
                    className="gallery-modal-color-dropdown-trigger"
                    onClick={() => setShowBrushColorDropdown(!showBrushColorDropdown)}
                  >
                    <div 
                      className="gallery-modal-color-preview"
                      style={{ backgroundColor: brushColor }}
                    />
                    <span className="gallery-modal-color-name">
                      {brushColors.find(c => c.value === brushColor)?.name}
                    </span>
                    <span className="gallery-modal-color-arrow">▼</span>
                  </button>
                  
                  {showBrushColorDropdown && (
                    <div className="gallery-modal-color-dropdown-menu">
                      {brushColors.map((color) => (
                        <button
                          key={color.value}
                          className={`gallery-modal-color-dropdown-item ${brushColor === color.value ? 'active' : ''}`}
                          onClick={() => {
                            setBrushColor(color.value);
                            setShowBrushColorDropdown(false);
                          }}
                        >
                          <div 
                            className="gallery-modal-color-preview"
                            style={{ backgroundColor: color.value }}
                          />
                          <span className="gallery-modal-color-name">{color.name}</span>
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            )}
            
            {/* 涂抹颜色选择 - 只在涂抹模式下显示 */}
            {activeTool === 'erase' && (
              <div className="gallery-modal-color-picker">
                <label>颜色:</label>
                <div className="gallery-modal-color-dropdown">
                  <button
                    className="gallery-modal-color-dropdown-trigger"
                    onClick={() => setShowEraseColorDropdown(!showEraseColorDropdown)}
                  >
                    <div 
                      className="gallery-modal-color-preview"
                      style={{ backgroundColor: eraseColor }}
                    />
                    <span className="gallery-modal-color-name">
                      {eraseColors.find(c => c.value === eraseColor)?.name}
                    </span>
                    <span className="gallery-modal-color-arrow">▼</span>
                  </button>
                  
                  {showEraseColorDropdown && (
                    <div className="gallery-modal-color-dropdown-menu">
                      {eraseColors.map((color) => (
                        <button
                          key={color.value}
                          className={`gallery-modal-color-dropdown-item ${eraseColor === color.value ? 'active' : ''}`}
                          onClick={() => {
                            setEraseColor(color.value);
                            setShowEraseColorDropdown(false);
                          }}
                        >
                          <div 
                            className="gallery-modal-color-preview"
                            style={{ backgroundColor: color.value }}
                          />
                          <span className="gallery-modal-color-name">{color.name}</span>
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            )}
            
            {/* 画笔宽度选择 - 只在画笔模式下显示 */}
            {activeTool === 'brush' && (
              <div className="gallery-modal-brush-size">
                <label>粗细:</label>
                <input
                  type="range"
                  min="1"
                  max="20"
                  value={brushWidth}
                  onChange={(e) => setBrushWidth(Number(e.target.value))}
                  className="gallery-modal-brush-slider"
                />
                <span className="gallery-modal-brush-size-value">{brushWidth}px</span>
              </div>
            )}
            
            {/* 涂抹宽度选择 - 只在涂抹模式下显示 */}
            {activeTool === 'erase' && (
              <div className="gallery-modal-brush-size">
                <label>粗细:</label>
                <input
                  type="range"
                  min="20"
                  max="60"
                  value={eraseWidth}
                  onChange={(e) => setEraseWidth(Number(e.target.value))}
                  className="gallery-modal-brush-slider"
                />
                <span className="gallery-modal-brush-size-value">{eraseWidth}px</span>
              </div>
            )}
            
            {selectedImageId && (
              <button
                className="gallery-modal-tool-btn gallery-modal-delete-btn"
                onClick={handleImageDelete}
                title="删除"
              >
                删除
              </button>
            )}
            <button
              className="gallery-modal-tool-btn gallery-modal-save-btn"
              onClick={handleSave}
              title="保存"
            >
              保存
            </button>
            <button
              className="gallery-modal-tool-btn gallery-modal-download-btn"
              onClick={handleDownload}
              title="下载"
            >
              下载
            </button>
            <button
              className="gallery-modal-tool-btn"
              onClick={handleClear}
              title="清空"
            >
              清空
            </button>
          </div>

          {/* 关闭按钮 */}
          <button
            className="gallery-modal-close-btn"
            onClick={onClose}
            title="关闭"
          >
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <line x1="18" y1="6" x2="6" y2="18"></line>
              <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
          </button>

          {/* 隐藏的文件输入 */}
          <input
            ref={fileInputRef}
            type="file"
            multiple
            accept="image/*"
            onChange={(e) => {
              if (e.target.files) {
                handleFileUpload(e.target.files);
              }
            }}
            style={{ display: 'none' }}
          />
        </div>

        {/* 画布区域 */}
        <div ref={canvasContainerRef} className="gallery-modal-canvas-container">
          <div 
            className="gallery-modal-canvas-area"
            ref={canvasRef}
            onDrop={handleDrop}
            onDragOver={handleDragOver}
          >
            <FabricCanvas
              images={images}
              onImagesChange={(newImages) => {
                setImages(newImages);
              }}
              activeTool={activeTool}
              onImageSelect={handleImageSelect}
              width={800} // 800px 弹窗宽度 - 40px padding
              height={524} // 600px 弹窗高度 - 100px 工具栏高度
              brushColor={activeTool === 'brush' ? brushColor : eraseColor}
              brushWidth={activeTool === 'brush' ? brushWidth : eraseWidth}
              ref={fabricCanvasRef}
            />
            
            {/* 加载指示器 */}
            {isLoadingImage && (
              <div className="gallery-modal-upload-overlay">
                <div className="gallery-modal-upload-spinner">
                  <div className="gallery-modal-upload-loading-indicator"></div>
                  <p>正在加载图片到画布...</p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>,
    document.body
  );
};

export default GalleryModal;
